/*
** sort_space_tab.c for sort_tab.c in /home/yang_j/rendu
** 
** Made by yang jie
** Login   <yang_j@epitech.net>
** 
** Started on  Wed Nov  6 19:33:16 2013 yang jie
** Last update Sat Dec  7 19:09:37 2013 georgi_v
*/

#include <stdlib.h>
#include "my.h"

int	my_word_len(int i, char *str, char c)
{
  int	j;

  j = 0;
  while (str[i] && str[i] != c)
    {
      j = j + 1;
      i = i + 1;
    }
  return (j);
}

int	my_word_nbr(char *str, char c)
{
  int	i;
  int	cnt;

  i = 0;
  cnt = 1;
  while (str[i])
    {
      if (str[i] == c)
	cnt = cnt + 1;
      i = i + 1;
    }
  cnt = cnt + 1;
  return (cnt);
}

char	*clear_space_in_line(char *str, int j)
{
  int	i;
  char	*dest;

  i = 0;
  if ((dest = malloc(my_strlen(str) * sizeof(dest))) == NULL)
    return (NULL);
  while (str[i] == ' ' || str[i] == '\t')
    i++;
  while (str[i] != '\0')
    {
      if ((str[i] == ' ' || str[i] == '\t') &&
	  ((str[i + 1] == ' ') || (str[i + 1] == '\t')));
      else
	{
	  dest[j] = str[i];
	  if (str[i] == '\t')
	    dest[j] = ' ';
	  j = j + 1;
      	}
      i = i + 1;
    }
  dest[j] = '\0';
  if (dest[my_strlen(dest) - 1] == ' ')
    dest[my_strlen(dest) - 1] = '\0';
  return (dest);
}

char	**put_in_tab(char *tmp, char c, char **dest, int i)
{
  int	j;
  int	k;

  j = 0;
  k = 0;
  while (tmp[++i])
    {
      if (tmp[i] == ' ' || tmp[i] == c)
	{
	  dest[j][k] = '\0';
	  j = j + 1;
	  k = 0;
	  if(tmp[i] == c && tmp[i + 1] == ' ')
	    i++;
	  if (tmp[i + 1] == c && tmp[i + 2] == ' ')
	    i = i + 2;
	  if (tmp[i + 1] == c && tmp[i + 2] != ' ')
	    i++;
	  dest[j] = malloc((my_word_len(i + 1, tmp, c) + 1) * sizeof(dest[j]));
	  if (dest[j] == NULL)
	    exit(-1);
	}
      else
	dest[j][k++] = tmp[i];
    }
  dest[j][k] = '\0';
  dest[j + 1] = NULL;
  return (dest);
}

char	**parse_line(char *str, char c)
{
  int	j;
  char	**dest;
  char	*tmp;

  j = 0;
  tmp = clear_space_in_line(str, j);
  dest = malloc((my_word_nbr(tmp, c) + 1) * sizeof(dest));
  if (dest == NULL)
    return (NULL);
  dest[0] = malloc((my_word_len(0, tmp, c) + 1) * sizeof(dest[0]));
  dest = put_in_tab(tmp, c, dest, -1);
  free(tmp);
  return (dest);
}
